﻿
using SHZY.Common.Filter;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.Business.Entitys.Dto.QmsBusiExemptionrulerecord;
using SHZY.Business.Entitys;
using SHZY.Business.Interfaces;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using SHZY.BaseData.Entitys;
using SHZY.Business.Entitys.Dto.QmsBusiInspectionlot;
using SHZY.Business.Entitys.Dto.Exemptionrulerecord;

namespace SHZY.Business;

/// <summary>
/// 业务实现：跳检规则记录.
/// </summary>
[ApiDescriptionSettings(Tag = "Business", Name = "Exemptionrulerecord", Order = 200)]
[Route("api/Business/[controller]")]
public class QmsBusiExemptionrulerecordService : IQmsBusiExemptionrulerecordService, IDynamicApiController, ITransient
{
    /// <summary>
    /// 服务基础仓储.
    /// </summary>
    private readonly ISqlSugarRepository<QmsBusiExemptionrulerecordEntity> _repository;


    /// <summary>
    /// 初始化一个<see cref="QmsBusiExemptionrulerecordService"/>类型的新实例.
    /// </summary>
    public QmsBusiExemptionrulerecordService(
        ISqlSugarRepository<QmsBusiExemptionrulerecordEntity> QmsBusiExemptionrulerecordRepository)
    {
        _repository = QmsBusiExemptionrulerecordRepository;
    }

    /// <summary>
    /// 获取跳检规则记录.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<dynamic> GetInfo(string id)
    {
        return (await _repository.FirstOrDefaultAsync(x => x.Id == id)).Adapt<QmsBusiExemptionrulerecordInfoOutput>();
    }

    /// <summary>
    /// 获取跳检规则记录列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("")]
    public async Task<dynamic> GetList([FromQuery] QmsBusiExemptionrulerecordListQueryInput input)
    {
        var queryable = _repository.Context.Queryable<QmsBusiExemptionrulerecordEntity, QmsBaseSupplierEntity,
            QmsBaseInspectionrolemainEntity, QmsBaseInspectionroleEntity>
            ((a, b, c, d) => new JoinQueryInfos(
                 JoinType.Left, a.SupplierNo == b.Code && b.DeleteMark == null,
                 JoinType.Left, a.RuleCode == c.Code && c.DeleteMark == null,
                 JoinType.Left, c.Id == d.MainId && a.Stage == d.Stage && d.DeleteMark == null
                ))
            .WhereIF(!string.IsNullOrEmpty(input.matnrCode), a => a.MatnrCode.Contains(input.matnrCode))
            .WhereIF(!string.IsNullOrEmpty(input.orderType), a => a.OrderType.Contains(input.orderType))
            .WhereIF(!string.IsNullOrEmpty(input.supplierNo), a => a.SupplierNo.Contains(input.supplierNo))
            .WhereIF(!string.IsNullOrEmpty(input.ruleCode), (a, b, c, d) => a.RuleCode.Contains(input.ruleCode) || c.Desc.Contains(input.ruleCode))
            .WhereIF(!string.IsNullOrEmpty(input.stage), (a, b, c, d) => a.Stage.Contains(input.stage) || d.StageDesc.Contains(input.stage))
            .WhereIF(!string.IsNullOrEmpty(input.keyword),
            a => a.MatnrCode.Contains(input.keyword) ||
            a.SupplierNo.Contains(input.keyword) ||
            a.RuleCode.Contains(input.keyword) ||
            a.Stage.Contains(input.keyword))
            .Where(a => a.DeleteMark == null)
            .Select((a, b, c, d) => new QmsBusiExemptionrulerecordListOutput
            {
                id = a.Id,
                matnrCode = a.MatnrCode,
                orderType = a.OrderType,
                supplierNo = b.Name,
                ruleCode = SqlFunc.MergeString(c.Desc, " ", c.Code),
                stage = SqlFunc.MergeString(d.StageDesc, " ", d.Stage),
                qualifiedInspNumber = a.QualifiedInspNumber,
                unqualifiedInspNumber = a.UnqualifiedInspNumber,
                creatorTime = a.CreatorTime,
            }).MergeTable();

        if (!string.IsNullOrEmpty(input.inspectionlotCode))
        {
            var detailList = await _repository.Context.Queryable<QmsBusiExemptionrulerecorddetailEntity, QmsBusiInspectionlotEntity>
             ((a, b) => new JoinQueryInfos(JoinType.Left, a.InspectionlotId == b.Id))
             .Where((a, b) => a.DeleteMark == null && a.EnabledMark == 1 && b.Code.Contains(input.inspectionlotCode)).Select(a => a.ParentId).ToListAsync();
            if (detailList.Count > 0)
            {
                queryable.Where(a => detailList.Contains(a.id));
            }
            else
            {
                queryable.Where(a => a.id == "-1");
            }

        }
        if (!string.IsNullOrEmpty(input.sidx))
        {
            queryable.OrderBy(input.sidx + " " + input.sort);
        }
        else
        {
            queryable.OrderBy(it => it.creatorTime, OrderByType.Desc);
        }

        var data = await queryable.ToPagedListAsync(input.currentPage, input.pageSize);
        return PageResult<QmsBusiExemptionrulerecordListOutput>.SqlSugarPageResult(data);
    }

    /// <summary>
    /// 获取跳检规则记录明细列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("detail")]
    public async Task<dynamic> GetDetailList([FromQuery] QmsBusiExemptionrulerecorddetailListQueryInput input)
    {
        var queryable = _repository.Context.Queryable<QmsBusiExemptionrulerecorddetailEntity, QmsBusiInspectionlotEntity, QmsBaseMaterialEntity, QmsBaseSupplierEntity>
            ((a, b, c, d) => new JoinQueryInfos(
                 JoinType.Left, a.InspectionlotId == b.Id,
                 JoinType.Left, b.MaterialCode == c.Code,
                 JoinType.Left, b.Supplier == d.Code
                ))
            .Where(a => a.ParentId== input.id && a.Status == input.status && a.DeleteMark == null)
            .OrderBy(a => a.CreatorTime, OrderByType.Asc);
        var data = await queryable.Select((a,b,c, d) => new QmsBusiInspectionlotListOutput
        {
            id = b.Id,
            code = b.Code,
            date = b.Date,
            type = b.Type,
            materialCode = b.MaterialCode,
            materialDes = c.Name,
            supplier = b.Supplier,
            supplierDes = d.Name,
            incomingQty = b.IncomingQty,
            batchNumber = b.BatchNumber,
            employeeCode = b.EmployeeCode,
            employeeName = b.EmployeeName,
            orderNo = b.OrderNo,
            inspectType = b.InspectType,
            remark = b.Remark,
            status = b.Status,
            judgeStatus = b.JudgeStatus,
            udNo = b.UdNo,
            decision = b.Decision,
            decisionName = b.DecisionName,
            destructivenessQty = b.DestructivenessQty,
            receiveQty = b.ReceiveQty,
            decisionDesc = b.DecisionDesc,
            overdue = b.Overdue,
            enabledMark = b.EnabledMark,
            parameter = b.Parameter,
            ruleCode = b.RuleCode,
            ruleDesc = b.RuleDesc,
            ruleStage = b.RuleStage,
            ruleStageDesc = b.RuleStageDesc,
            startTime = b.StartTime,
            endTime = b.EndTime,
        }).ToPagedListAsync(input.currentPage, input.pageSize);
        return PageResult<QmsBusiInspectionlotListOutput>.SqlSugarPageResult(data);
    }
}